//
//  OTDR_SocketServer.m
//  OTDR
//
//  Created by Liu on 2024/5/23.
//

#import "OTDR_SocketServer.h"


@implementation OTDR_SocketServer
{
    int kTcpFCPort;
    NSString *kTCPIP;
}
static OTDR_SocketServer *hgFcTcpsocket = nil;

static dispatch_once_t onceToken;
+ (instancetype)sharedInstance {
    dispatch_once(&onceToken, ^{
        hgFcTcpsocket = [[self alloc] init];
    });
    return hgFcTcpsocket;
}//初始化
- (instancetype)init
{
    if (self = [super init]) {
        _asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    }
    return self;
}

/**
 * 关闭HGFCTCPSocketServe
 */
-(void)stopConnect{

    if(_connectTimer!=nil)
    {
        dispatch_source_cancel(_connectTimer);
        _connectTimer = nil;
    }
    [_asyncSocket disconnect];
}

//连接socket 地址 端口号
- (void)connectWithHost:(NSString *)hostName port:(int)port
{
    
    kTCPIP = hostName;
    kTcpFCPort = port;
    
    
    reConnectCount=0;
    NSError *error = nil;
    if ([self isFCDisConnect])
    {
        [_asyncSocket connectToHost:hostName onPort:port withTimeout:4.0 error:&error];
        NSLog(@"%@",[NSString stringWithFormat:@"开始连接:%@ %d",hostName,port]);
    }
    if (error) {
         NSLog(@"%@",[NSString stringWithFormat:@"5000连接错误:%@",error]);
        if (self.connectIsSuccessBlock) {
            self.connectIsSuccessBlock(NO);
        }
        //正常需要重练几次，但此项目暂不做此功能
        [self reConnect];
    }
}

//是否连接
- (BOOL)isFCDisConnect
{
    return [_asyncSocket isDisconnected];
}

//读
- (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag
{
    [_asyncSocket readDataWithTimeout:-1 tag:tag];
}

//写
- (void)writeToFCTCPWithData:(NSData *)data;
{
 
    [_asyncSocket writeData:data withTimeout:-1 tag:kTcpFCPort];
    
}

#pragma mark GCDAsyncSocketDelegate method
//断开连接代理
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    NSLog(@"5000 断开");
    if (self.connectIsSuccessBlock) {
        self.connectIsSuccessBlock(NO);
    }
    reConnectCount++;
    [self reConnect];
   
}
//连接成功代理
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {

    NSLog(@"5000 端口连接成功");

    if(_connectTimer!=nil)
    {
        dispatch_source_cancel(_connectTimer);
        _connectTimer = nil;
    }
    
    if (self.connectIsSuccessBlock) {
        self.connectIsSuccessBlock(YES);
    }
    
    [sock readDataWithTimeout:-1 tag:kTcpFCPort];
}

//读数据成功代理
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    if ([self.delegate respondsToSelector:@selector(didReadData:withTag:)]) {
        [self.delegate didReadData:data withTag:tag];
    }
    
    [sock readDataWithTimeout:-1 tag:tag];
}
///发送消息成功之后回调
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag {
    
    [sock readDataWithTimeout:-1 tag:kTcpFCPort];
}

//断开重连方法
-(void)fcConnectTimerStart{
   
    @autoreleasepool {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"5000 重新连接");
            [self connectWithHost:self->kTCPIP port:self->kTcpFCPort];
        });
    }
}


//重连线程
-(void)reConnect{
    return;//禁止反复重连
    if(_connectTimer!=nil)
    {
        dispatch_source_cancel(_connectTimer);
        _connectTimer = nil;
    }
    if(reConnectCount>6){
        reConnectCount=6;
    }
    
    _connectQueue = dispatch_queue_create("_reConnectFCQueue", NULL);
    _connectTimer= dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _connectQueue);
    //开始时间
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, 3.0 * NSEC_PER_SEC);
    //间隔时间
    uint64_t interval = NSEC_PER_SEC * reConnectCount;
    dispatch_source_set_timer(_connectTimer, start, interval, 0);
    //设置回调
    __weak __typeof__(self) weakSelf = self;
    dispatch_source_set_event_handler(_connectTimer, ^{
        [weakSelf fcConnectTimerStart];
    });
    //启动timer
    dispatch_resume(_connectTimer);
}

-(void)DeallocAll
{
    [_asyncSocket disconnect];
    _asyncSocket.delegate=nil;
    _asyncSocket=nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"Dealloc  hgfctcpsocket");
    hgFcTcpsocket=nil;
    onceToken=0;
}


@end
